<template>
	<xn-form-container
		:title="formData.id ? '编辑分类' : '增加分类'"
		:width="550"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="上级分类：" name="parentId">
				<a-tree-select
					v-model:value="formData.parentId"
					style="width: 100%"
					:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
					placeholder="请选择上级分类"
					allow-clear
					tree-default-expand-all
					:tree-data="treeData"
					:field-names="{
						children: 'children',
						label: 'categoryName',
						value: 'id'
					}"
					selectable="false"
					tree-line
				/>
			</a-form-item>
			<a-form-item label="分类名称：" name="categoryName">
				<a-input v-model:value="formData.categoryName" placeholder="请输入分类名称" allow-clear />
			</a-form-item>
			<a-form-item label="分类描述：" name="categoryDesc">
				<a-textarea :rows="8" v-model:value="formData.categoryDesc" placeholder="请输入分类描述" allow-clear />
			</a-form-item>
			<a-form-item label="排序：" name="sort">
				<a-input-number style="width: 100%" v-model:value="formData.sort" :max="100" />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup >
import { required } from '@/utils/formRules'
import tool from '@/utils/tool'
import bizCategoryApi from "@/api/biz/bizCategoryApi";

// 定义emit事件
const emit = defineEmits({ successful: null })
// 默认是关闭状态
const visible = ref(false)
let UserSelectorPlus = ref()
const formRef = ref()
// 表单数据，也就是默认给一些数据
const formData = ref({})
// 定义分类元素
const treeData = ref([])
const submitLoading = ref(false)

// 打开抽屉
const onOpen = (record, parentId) => {
	visible.value = true
	formData.value = {
		sortCode: 99
	}
	if (parentId) {
		formData.value.parentId = parentId
	}
	if (record) {
		const param = {
			id: record.id
		}
		bizCategoryApi.bizCategoryDetail(param).then((data) => {
			formData.value = Object.assign({}, data)
		})
	}
	// 获取分类树并加入顶级
	bizCategoryApi.tree().then((res) => {
		treeData.value = [
			{
				id: 0,
				parentId: '-1',
				categoryName: '全部',
				children: res
			}
		]
	})
}
// 关闭抽屉
const onClose = () => {
	visible.value = false
}
// 默认要校验的
const formRules = {
	categoryName: [required('请输入分类名称')],
	categoryDesc: [required('请选择分类描述')],
	sort: [required('请输入排序')]
}


// 验证并提交数据
const onSubmit = () => {
	formRef.value
		.validate()
		.then(() => {
			submitLoading.value = true
			bizCategoryApi
				.bizCategorySubmitForm(formData.value, formData.value.id)
				.then(() => {
					visible.value = false
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
		.catch(() => {})
}

defineExpose({
	onOpen
})
</script>
